import { Component } from "react"

class TodoList extends Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this)
    this.handleChange = this.handleChange.bind(this)
    this.state = {
      itemText: "",
      list: []
    }
  }

  handleSubmit() {
    // console.log(this)
    // console.log(this.state.itemText)
    // m -> v
    // 返回新数据
    if (!this.state.itemText || this.state.list.includes(this.state.itemText)) {
      return
    }
    this.setState({
      list: [...this.state.list, this.state.itemText],
      itemText: ""
    })
  }

  handleChange(event) {
    this.setState({
      itemText: event.target.value
    })
  }

  render() {

    let todoListHtml
    if (this.state.list.length === 0) {
      todoListHtml = "暂无数据"
    } else {
      todoListHtml = this.state.list.map(item => <li key={item}>{item}</li>)
    }

    return (
      <div className={"todo"}>
        <h1>Todo</h1>
        <div>
          {/* react 单项数据流 */}
          <input
            type="text"
            value={this.state.itemText}
            onChange={this.handleChange}
          />
          <button onClick={this.handleSubmit}>Add</button>
        </div>
        <ul>
          { todoListHtml }
        </ul>
        {/*<ol>
          { this.state.list.length === 0 && "暂无数据" }
          { this.state.list.length !== 0 && todoListHtml }
        </ol>
        <hr/>
        <ul>
          {this.state.list.length === 0
            ? "暂无数据"
            : todoListHtml
          }
        </ul>
        <hr/>
        <ul>
          {this.state.list.length === 0
            ? "暂无数据"
            : this.state.list.map(item => <li key={item}>{item}</li>)}
        </ul>
        <hr/>
        <ul>
          {this.state.list.map(item => {
            return <li key={item}>{item}</li>
          })}
        </ul>*/}
      </div>
    )
  }
}

export default TodoList

